import Const from './const'

function Data() {
  return {
    set: set,
    get: get,
    remove: remove,
    getKey: getKey,
    setToken: setToken,
    getToken: getToken,
    setUser: setUser,
    getUser: getUser,
    clearAuthData: clearAuthData
  };


  function getKey(key) {
    return Const.DATA.KEY_PREFIX + key;
  }

  function get(key) {
    if (key) {
      key = getKey(key);
      return JSON.parse(window.localStorage.getItem(key));
    }
  }

  function set(key, val) {
    if (key) {
      key = getKey(key);
      return window.localStorage.setItem(key, JSON.stringify(val));
    }
  }

  function remove(key) {
    if (key) {
      key = getKey(key);
      return window.localStorage.removeItem(key);
    }
  }

  function setToken(token) {
    if (token) {
      let key = getKey(Const.DATA.KEY_TOKEN);
      return window.localStorage.setItem(key, token);
    }
  }

  function getToken() {
    let key = getKey(Const.DATA.KEY_TOKEN);
    return window.localStorage.getItem(key);
  }

  function setUser(user) {
    let key = getKey(Const.DATA.KEY_USER);
    return set(key, user);
  }

  function getUser() {
    let key = getKey(Const.DATA.KEY_USER);
    return get(key);
  }

  function clearAuthData() {
    setToken('');
    setUser('');
  }
}

export default new Data();
